const router = require('koa-router')();
const scripts = require('./scripts/publish');

router.prefix('/api/publish', '发布管理相关');

router.get('/configs', async (ctx, next) => {
  let rs = await ctx.sqlite.queryForList(scripts.getConfigs);

  ctx.body = rs;
}, '获取所有配置信息');

router.post('/save', async (ctx, next) => {
  let info = ctx.request.body || {};

  if (!info.category) {
    ctx.body = ctx.getResponse('分类不能为空！');

    return;
  }

  let res = await ctx.sqlite.queryForObject(scripts.getConfig, { category: info.category });

  if (res.data) {
    info.id = res.data.Id;

    await ctx.sqlite.execute(scripts.updateConfig, info);
  } else {
    await ctx.sqlite.execute(scripts.addConfig, info);
  }

  ctx.body = ctx.getResponse();
}, {
  desc: '保存配置信息', body: {
    category: { type: 'string', desc: '分类' },
    gitBranch: { type: 'string', desc: 'Git分支获取命令' },
    buildCommand: { type: 'string', desc: '生成本地镜像命令' },
    onlineCommand: { type: 'string', desc: '发布上线命令' },
    getBuildVersions: { type: 'string', desc: '获取本地版本命令' },
    getOnlineVersions: { type: 'string', desc: '获取已上线版本命令' },
    harborRepositoryUrl: { type: 'string', desc: 'Harbor镜像库地址' }
  }
});

router.delete('/:id', async (ctx, next) => {
  let rs = await ctx.sqlite.execute(scripts.removeConfig, { id: ctx.params.id });

  ctx.body = rs;
}, { desc: '删除配置信息', id: '配置编号' });

module.exports = router;